from rest_framework import serializers
from . models import User
import re
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings


from .utils import generate_email_verify_url
from celery_tasks.email.tasks import send_verify_email
from .models import Address
from goods.models import SKU

class CreateUserSerializer(serializers.ModelSerializer):
    """注册序列化器"""
    #自定义模型
    password2 = serializers.CharField(label='密码2', write_only=True)
    sms_code = serializers.CharField(label='验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)

    token = serializers.CharField(label='登录状态token', read_only=True) # 增加token字段

    """
        序列化器中需要的所有字段: 'id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow'
        模型中已有字段: id', 'username', 'mobile', 'password'
        需要进行反序列化的字段: 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow'
        需要进行序列化的字段:  'id', 'username', 'mobile'
    """

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'password', 'password2', 'sms_code', 'allow','token']
        extra_kwargs={# 对序列化器中的字段进行额外配置
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {  # 自定义反序列化校验错误信息
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,  # 只做反序列化
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        """对手机号单独追加校验逻辑"""
        if not re.match(r'1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机号格式有误')
        return value

    def validate(self, attrs):
        """对两个密码进行判断"""
        if attrs.get('password') != attrs.get('password2'):
            raise serializers.ValidationError('两次密码不一致')

        #校验验证码
        mobile = attrs.get('mobile')
        #创建redis连接
        redis_conn = get_redis_connection('verify_codes')
        real_sms_code = redis_conn.get('sms_%s' % mobile)
        # 向redis存储数据时,都是以字符串的格式存储进行,将来获取出来后,
        # 都会变成'bytes'类型: str: bytes hash: {b'key':b''} list:[b'',] set:[b'']
        if not real_sms_code:
            raise serializers.ValidationError('验证码过期')
        # 此处一定要注意从redis中取出来的字符串是bytes类型需要转换成str
        if real_sms_code.decode() != attrs.get('sms_code'):
            raise serializers.ValidationError('验证码有误')

        return attrs

    def create(self, validated_data):
        """重写序列化器的保存方法把多余数据移除"""

        # 移除数据库模型类中不存在的属性
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']

        password = validated_data.pop('password') #把字典中的password移除

        user = User(**validated_data)
        user.set_password(password) #对密码进行加密后再赋值给user模型对象的password属性
        user.save()


        #补充生成记录登录状态的token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载生成载荷函数
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token的函数

        payload = jwt_payload_handler(user)  # 通过传入user对象生成jwt 载荷部分
        token = jwt_encode_handler(payload)  # 传入payload 生成token
        # 给user 模型对象多增加一个token属性,再给序列化器多增加token字段只做序列化
        user.token = token

        return user



class UserDetailSerializer(serializers.ModelSerializer):
    """用户信息展示序列化器"""

    class Meta:
        model = User
        fields = ['id', 'username', 'mobile', 'email', 'email_active']


class EmailSerializer(serializers.ModelSerializer):
    """设置邮箱"""

    class Meta:
        model = User
        fields = ['id', 'email']
        # 因为email字段在模型中定义时,设置的可以为空,那么ModelSerializer在自动生成字段时,
        # 如果模型中设置字段可以为空,或有默认值,那么它required默认就会生成为False
        extra_kwargs = {
            'email' :{'required' : True}
        }

    def update(self, instance, validated_data):
        # 设置属性
        instance.email = validated_data.get('email')
        # 保存
        instance.save()

        verify_url = generate_email_verify_url(instance)

        send_verify_email.delay(instance.email, verify_url)

        return instance


class AddressSerializer(serializers.ModelSerializer):
    """收货地址序列化器"""

    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ['user', 'is_deleted', 'create_time', 'update_time']

    def validate_mobile(self, value):
        """验证手机号"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')

        return value

    def create(self, validated_data):
        user = self.context['request'].user  # 获取到user
        validated_data['user'] = user  # 把user添加到字典中
        return Address.objects.create(**validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """地址标题"""
    class Meta:
        model = Address
        fields= ['title']



class UserBrowseHistorySerializer(serializers.Serializer):

    """保存浏览记录"""
    #自定义一个商品id的序列化模型
    sku_id = serializers.IntegerField(label='sku商品id', min_value=1)

    def validate_sku_id(self, value):
        """追加额外检验逻辑"""
        try:
            SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('sku_id不存在')
        return value

    def create(self, validated_data):
        """重写此方法把浏览记录存储到redis数据库"""
        sku_id = validated_data.get('sku_id')
        #获取当前的用户user
        user = self.context['request'].user
        print(self.context['request'])

        # user = self.context['view'].user


        # 创建redis连接对象
        redis_conn = get_redis_connection('history')
        #创建管道对象
        pl = redis_conn.pipeline()
        # 先去重  lrem()
        pl.lrem('histroy_%s' % user.id, 0, sku_id)
        print(user.id)
        #添加 lpush()
        pl.lpush('history_%s' % user.id, sku_id)
        # 截取前5个 ltrim()
        pl.ltrim('history_%s' % user.id, 0, 4)
        print(user.id)
        # 执行管道
        pl.execute()
        #返回
        return validated_data